﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Data.Services.Client;
using Social_Photos.Social_Photos_Services;

namespace Social_Photos
{
    public class MainViewModel : INotifyPropertyChanged
    {
        // Set the string of your streaming service implementation.
        //*****update this to your own streaming service implementation*****
        static string serviceUriString =
            "http://localhost/SocialPhotos/PhotoCloud.svc/";

        // Declare the service root URI.
        private Uri svcRootUri =
            new Uri(serviceUriString, UriKind.Absolute);

        // Declare our private binding collection.
        private DataServiceCollection<Photo> _photos;

        // Declare the DataServiceContext as private.
        private SocialPhotoModelContainer _context;

        public bool IsDataLoaded { get; private set; }

        // Loads data from the data service for the first time.
        public void LoadData()
        {
            // Instantiate the context and binding collection.
            _context = new SocialPhotoModelContainer(svcRootUri);
            Photos = new DataServiceCollection<Photo>(_context);

            // Load the data from the PhotoInfo feed.
            Photos.LoadAsync(new Uri("/Photos", UriKind.Relative));
        }

        // Provides data to the ViewModel with the provided objects, 
        // which enables us to restore the ViewModel after reactivation.
        public void LoadData(SocialPhotoModelContainer context, DataServiceCollection<Photo> photos)
        {
            this._context = context;
            this.Photos = photos;
            Photo a = new Photo();
            
            IsDataLoaded = true;
        }

        public void LoadDataTop6()
        {
            // Instantiate the context and binding collection.
            _context = new SocialPhotoModelContainer(svcRootUri);
            Photos = new DataServiceCollection<Photo>(_context);
          
            // Load the data from the Photo feed.
            Photos.LoadAsync(new Uri("/getRandomPhotos?number=6", UriKind.Relative));

        }

        // Public collection used for data binding.
        public DataServiceCollection<Photo> Photos
        {
            get
            {
                return _photos;
            }
            set
            {
                _photos = value;

                // Report the change in the binding collection.
                NotifyPropertyChanged("Photos");

                // Register a handler for the LoadCompleted event.
                _photos.LoadCompleted +=
                    new EventHandler<LoadCompletedEventArgs>(Photos_LoadCompleted);
            }
        }

        // Handles the LoadCompleted event.
        private void Photos_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                // Make sure that we load all pages of the Customers feed.
                if (_photos.Continuation != null)
                {
                    // Request the next page from the data service.
                    _photos.LoadNextPartialSetAsync();
                }
                else
                {
                    List<TopPhotosListBox> photoList = new List<TopPhotosListBox>();
                    for (int i = 0; i < Photos.Count; i++)
                    {
                       
                        Photo info = Photos[i];
                        Uri uri = new Uri("http://localhost/SocialPhotos/Thumbnail.ashx?f=" + info.FileName);
                        photoList.Add(new TopPhotosListBox(uri.ToString(), info.FileName, info.Id,info.Likes,info.Dislikes));
                    }
            
                    
                    //Photo a = Photos[2];
                
                    // All pages are loaded.
                    IsDataLoaded = true;
                }
            }
            else
            {
                if (MessageBox.Show(e.Error.Message, "Retry request?",
                    MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    this.LoadData();
                }
            }
        }

        // Returns the URI of the media resource for the provided media link entry.
        public Uri GetReadStreamUri(object entity)
        {
            // Return the URI of the media resource.
            return this._context.GetReadStreamUri(entity);
        }

        // Change notification event that is handled by the binding.
        public event PropertyChangedEventHandler PropertyChanged;

        // Notifies the binding about a changed property value.
        private void NotifyPropertyChanged(string propertyName)
        {
            var propertyChanged = PropertyChanged;
            if (propertyChanged != null)
            {
                // Raise the PropertyChanged event.
                propertyChanged(this,
                    new PropertyChangedEventArgs(propertyName));
            }
        }


        private void OnExecuteCompleted(IAsyncResult result)
        {
            // Use the Dispatcher to ensure that the response is
            // marshaled back to the UI thread.
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                try
                {
                    // Complete the query by assigning the returned
                    // entity, which materializes the new instance 
                    // and attaches it to the context. We also need to assign the 
                    // new entity in the collection to the returned instance.
                    Photo entity = _photos[_photos.Count - 1] =
                        _context.EndExecute<Photo>(result).FirstOrDefault();

                    // Report that that media resource URI is updated.
                    entity.ReportStreamUriUpdated();
                }
                catch (DataServiceQueryException ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    // Raise the event by using the () operator.
                    if (SaveChangesCompleted != null)
                    {
                        SaveChangesCompleted(this, new AsyncCompletedEventArgs());
                    }
                }
            });
        }

        // Declare a delegate for the SaveChangesCompleted event.
        public delegate void SaveChangesCompletedEventHandler(object sender, AsyncCompletedEventArgs e);

        // Declare the event.
        public event SaveChangesCompletedEventHandler SaveChangesCompleted;
    }
}
